package com.example.rwq_test.niuke.list;

/**
 * TODO note
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2023/10/18
 */
public class removeNthFromEnd {

    public static void main(String[] args) {
        ListNode dummy = new ListNode(-1);
        ListNode head = new ListNode(1);
        dummy.next = head;
        for (int i = 2; i < 10; i++) {
            ListNode listNode = new ListNode(i);
            head.next = listNode;
            head = head.next;
        }

        removeNthFromEnd(dummy.next, 4);

        while (dummy != null) {
            System.out.println(dummy.val);
            dummy = dummy.next;
        }
    }

    public static void  removeNthFromEnd (ListNode head, int n) {
        if (n == 0) {
            return;
        }
        int index = -1;
        ListNode p = head;
        while (p != null && index < n) {
            p = p.next;
            index++;
        }
        if (p == null) {
            head = null;
            return;
        }

        ListNode q = head;
        while (p != null) {
            p = p.next;
            q = q.next;
        }
        q.next = null;
    }

}
